package com.tjian.fafa.user.module.courier.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.tjian.fafa.user.R;
import com.tjian.fafa.user.config.Action_url_fafa;
import com.tjian.fafa.user.module.bean.BaseBean;
import com.tjian.fafa.user.module.callback.ResultCallback;
import com.tjian.fafa.user.module.courier.adapter.ListViewAdapter;
import com.tjian.fafa.user.module.courier.bean.MoodInBean;
import com.tjian.fafa.user.module.courier.bean.MoodInfoBean;
import com.tjian.fafa.user.module.courier.bean.UserBean;
import com.tjian.fafa.user.module.courier.receiver.MyPushMessageReceiver;
import com.tjian.fafa.user.module.courier.service.UpdateService;
import com.tjian.fafa.user.module.courier.util.CourierUtil;
import com.tjian.fafa.user.module.courier.util.HttpUtil;
import com.tjian.fafa.user.module.courier.util.TimeUtil;
import com.tjian.fafa.user.module.courier.view.AlwaysMarqueeTextView;
import com.tjian.fafa.user.module.home.result.HomeResult;
import com.tjian.fafa.user.module.listview.XListView;
import com.tjian.fafa.user.module.listview.XListView.IXListViewListener;

//import org.apache.http.NameValuePair;
//import org.apache.http.message.BasicNameValuePair;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import cz.msebera.android.httpclient.NameValuePair;
import cz.msebera.android.httpclient.message.BasicNameValuePair;

public class AroundCourierActivity extends BaseActivity implements OnClickListener, IXListViewListener
{
    private Context mContext = this;
    private ListView mListView;
    private List<HomeResult> nearbyCarDataList = new ArrayList<HomeResult>();//查看周边的专车。
    private List<HomeResult> friendDynamicDataList = new ArrayList<HomeResult>();//好友动态数据
    private LinearLayout order_by_distance_linearLayout;
    private LinearLayout friendDynamicLinearLayout;
    private XListView myListView;
    private Context context;
    private LayoutInflater layoutInflater;
    private UserBean userBean;
    private RelativeLayout layoutStr;
    private AlwaysMarqueeTextView alwaysStr;
    private int LOAD_REFRESH = 0;
    private List<MoodInfoBean> allMoodInfo = new ArrayList<MoodInfoBean>();
    private int LOAD_MORE = 1;
    private int page = 1;
    MoodInfoBean moodInfo;
    private ListViewAdapter myListViewAdapter = null;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        //		buttonFunctions();
        setContentView(R.layout.main);
        layoutInflater = LayoutInflater.from(this);
        context = this;
        Intent updateServiceIntent = new Intent(this, UpdateService.class);
        startService(updateServiceIntent);
        initData();
        initViews();
    }

    public void buttonFunctions()
    {
        //		mListView = (ListView)findViewById(R.id.tabHomeListView);
        order_by_distance_linearLayout = (LinearLayout) findViewById(R.id.order_by_distance_linearLayoutId);
        friendDynamicLinearLayout = (LinearLayout) findViewById(R.id.friendDynamicLinearLayoutId);

        //默认加载按距离远近的。
        nearbyCarDataList = CourierUtil.getFriendDynamicDataList(mContext, nearbyCarDataList); //加载数据。
        CourierUtil.friendDynamicUpdateView(mContext, mListView, nearbyCarDataList);

        //测试从网络获取数据。
        //		myListView = (XListView)findViewById(R.id.myListView);
        //		CourierUtil.getData(mContext, myListView,nearbyCarDataList,0);

        order_by_distance_linearLayout.setOnClickListener(new OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                nearbyCarDataList = CourierUtil.getFriendDynamicDataList(mContext, nearbyCarDataList);
                CourierUtil.friendDynamicUpdateView(mContext, mListView, nearbyCarDataList);
            }
        });
        friendDynamicLinearLayout.setOnClickListener(new OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                friendDynamicDataList = CourierUtil.getFriendDynamicDataList(mContext, friendDynamicDataList);
                CourierUtil.friendDynamicUpdateView(mContext, mListView, friendDynamicDataList);
            }
        });

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event)
    {
        //如果按下的是返回键，并且没有重复
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0)
        {
            finish();
            overridePendingTransition(R.anim.slide_up_in, R.anim.slide_down_out);
            return false;
        }
        return false;
    }

    /* ViewPager适配器 */
    public class MyPagerAdapter extends PagerAdapter
    {
        public List<View> mListViews;

        public MyPagerAdapter(List<View> mListViews)
        {
            this.mListViews = mListViews;
        }

        @Override
        public void destroyItem(View arg0, int arg1, Object arg2)
        {
            ((ViewPager) arg0).removeView(mListViews.get(arg1));
        }

        @Override
        public void finishUpdate(View arg0)
        {
        }

        @Override
        public int getCount()
        {
            return mListViews.size();
        }

        @Override
        public Object instantiateItem(View arg0, int arg1)
        {
            ((ViewPager) arg0).addView(mListViews.get(arg1), 0);
            return mListViews.get(arg1);
        }

        @Override
        public boolean isViewFromObject(View arg0, Object arg1)
        {
            return arg0 == (arg1);
        }

        @Override
        public void restoreState(Parcelable arg0, ClassLoader arg1)
        {
        }

        @Override
        public Parcelable saveState()
        {
            return null;
        }

        @Override
        public void startUpdate(View arg0)
        {
        }
    }

    @Override
    public void initData()
    {
        super.initData();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(MyPushMessageReceiver.MESSAGE_ACTION);
        registerReceiver(messageReceiver, intentFilter);
        UserBean u = (UserBean) getIntent().getSerializableExtra("user");
        this.userBean = u;
    }

    @Override
    protected void onStart()
    {
        super.onStart();
    }

    @Override
    public void onRefresh()
    {
        loadData(LOAD_REFRESH);
    }

    @Override
    public void onLoadMore()
    {
        loadData(LOAD_MORE);
    }

    @Override
    public void onClick(View v)
    {
    }

    BroadcastReceiver messageReceiver = new BroadcastReceiver()
    {
        @Override
        public void onReceive(Context arg0, Intent action)
        {
            if (action.getAction().equals(MyPushMessageReceiver.MESSAGE_ACTION))
            {
                String message = action.getStringExtra("message");
                if (!message.isEmpty())
                {
                    layoutStr.setVisibility(View.VISIBLE);
                    alwaysStr.setText("系统消息:" + message);
                }
            }
        }
    };

    @Override
    public void initViews()
    {
        super.initViews();
        layoutStr = (RelativeLayout) findViewById(R.id.layoutButtom);
        alwaysStr = (AlwaysMarqueeTextView) findViewById(R.id.alwaysStr);
        myListView = (XListView) findViewById(R.id.myListView);
        myListView.setPullLoadEnable(true);
        loadData(LOAD_REFRESH);
        myListView.setXListViewListener(this);
    }

    public void loadData(final int code)
    {
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("date", TimeUtil.getCurrentDate()));
        if (code == LOAD_MORE)
        {
            params.add(new BasicNameValuePair("page", String.valueOf(page)));
        }
        else if (code == LOAD_REFRESH)
        {
            page = 1;
            params.add(new BasicNameValuePair("page", String.valueOf(page)));
        }
        initProgressDialog();
        HttpUtil.doPost(Action_url_fafa.getAroundCourier_url, params, new ResultCallback()
        {
            @Override
            public void getReslt(String result)
            {
                if (result != null && !"1".equals(result))
                {
                    BaseBean bean = JSON.parseObject(result, BaseBean.class);

                    if (bean.getRespcode().equals("0"))
                    {
                        Type type = new TypeToken<MoodInBean>()
                        {
                        }.getType();
                        Gson gson = new Gson();
                        MoodInBean json = gson.fromJson(result, type);
                        List<MoodInfoBean> allData = json.getData();
                        if (allData.size() > 0)
                        {
                            final List<MoodInfoBean> allMoodInfoList = new ArrayList<MoodInfoBean>();
                            page++;
                            if (code == LOAD_REFRESH)
                            {
                                allMoodInfo.clear();
                                for (int i = 0; i < allData.size(); i++)
                                {
                                    setBean(allData, i);
                                    allMoodInfoList.add(moodInfo);
                                }
                                for (MoodInfoBean moodInfoBean : allMoodInfoList)
                                {
                                    allMoodInfo.add(moodInfoBean);
                                }
                                myListViewAdapter = new ListViewAdapter(AroundCourierActivity.this, allMoodInfo);
                                myListView.setAdapter(myListViewAdapter);
                            }
                            else if (code == LOAD_MORE)
                            {
                                for (int i = 0; i < allData.size(); i++)
                                {
                                    setBean(allData, i);
                                    allMoodInfo.add(moodInfo);
                                }
                                myListViewAdapter.notifyDataSetChanged();
                            }

                            onLoad();
                            close();
                        }
                        else
                        {
                            close();
                            Toast.makeText(AroundCourierActivity.this, "没有更多数据",
                                    Toast.LENGTH_LONG).show();
                            onLoad();
                        }
                    }
                    else
                    {
                        close();
                        Toast.makeText(AroundCourierActivity.this, "失败",
                                Toast.LENGTH_LONG).show();
                    }
                }
                else
                {
                    close();
                    Toast.makeText(AroundCourierActivity.this, "服务器响应失败", Toast.LENGTH_LONG).show();
                }
            }
        });
    }

    private void setBean(List<MoodInfoBean> allData, int i)
    {
        moodInfo = new MoodInfoBean();
        moodInfo.setAllComment(allData.get(i).getAllComment());
        moodInfo.setContent(allData.get(i).getContent());
        moodInfo.setDate(allData.get(i).getDate());
        moodInfo.setId(allData.get(i).getId());
        moodInfo.setImgfive(allData.get(i).getImgfive());
        moodInfo.setImgfour(allData.get(i).getImgfour());
        moodInfo.setImgone(allData.get(i).getImgone());
        moodInfo.setImgsix(allData.get(i).getImgsix());
        moodInfo.setImgthree(allData.get(i).getImgthree());
        moodInfo.setImgtwo(allData.get(i).getImgtwo());
        moodInfo.setTime(allData.get(i).getTime());
        moodInfo.setUserid(allData.get(i).getUserid());
        moodInfo.setContent(allData.get(i).getContent());
        moodInfo.setAge(allData.get(i).getAge());

        moodInfo.setAvatarImagePath(allData.get(i).getAvatarImagePath());
        moodInfo.setUserName(allData.get(i).getUserName());
        moodInfo.setAnkuaiNumber("发发号：" + allData.get(i).getAnkuaiNumber());
        moodInfo.setAccumulativeDeliveryTimes("累计送达数：" + allData.get(i).getAccumulativeDeliveryTimes());
        moodInfo.setAverageDeliveryTime("平均送达时间：" + allData.get(i).getAverageDeliveryTime() + "分钟");
        moodInfo.setApplauseRate("好评率：" + allData.get(i).getApplauseRate() + "%");
    }

    private void onLoad()
    {
        myListView.stopRefresh();
        myListView.stopLoadMore();
        myListView.setRefreshTime("刚刚");
    }

    @Override
    public void onDestroy()
    {
        super.onDestroy();
        unregisterReceiver(messageReceiver);
    }
}
